<?

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

portal_start();

if (empty($portal['count'])) {
	header("HTTP/1.1 503 Service Unavailable");
	customNoCacheHeader('nocache');
	print "not ready yet, check back later";
	exit;
}

$cachepath = "cache/heatmap.$portal_id.csv";
$expires = 3600*24;
setupCacheForOutput();

##will setup caching for the output regardless of output encoding. 
function setupCacheForOutput() {
	global $cachepath,$expires;

	 if (!empty($cachepath)) {

                //because we about to use this in the shutdown function make it total
                $cachepath = trim(`pwd`)."/".$cachepath;

                $encoding = getEncoding();
                if ($encoding) {
                        $cachepath .= ".$encoding";
                }

                if (file_exists($cachepath) && empty($_GET['refresh'])) {
                        $mtime = @filemtime($cachepath);

                        customExpiresHeader(empty($expires)?(3600*24*24):$expires,true);
                        customCacheControl($mtime,$cachepath);

                        header ('Content-Encoding: '.$encoding);
                        header ('Vary: Accept-Encoding');

                        header('Content-length: '.filesize($cachepath));

                        readfile($cachepath);

                        exit;
                }
        }

	//sets up the ob and the shutdown function that writes the cache file

	if (!customGZipHandlerStart()) {
		ob_start();
                register_shutdown_function('customGZipHandlerEnd');
	}


        if (!empty($expires)) {
                customExpiresHeader($expires,true);
        }
}



$sql = array();
$sql['columns'] = 'gridimage_id,wgs84_lat,wgs84_long';
$sql['tables'] = array();
$sql['tables'][] = "p2.gridimage{$portal_id}_bi_view";
$sql['wheres'] = array();

	$query = sqlMakeQuery($sql);

	$data = getAssoc($query);

	if ($data) {
		print "id,lat,long\n";
		foreach ($data as $id => $row) {
			print "{$id},{$row['wgs84_lat']},{$row['wgs84_long']}\n";
		}
	} else {
		die("nothing to see here");
	}

